from django.conf import settings
from django.shortcuts import HttpResponse, redirect
from django.utils.deprecation import MiddlewareMixin
import re

class RbacMiddleware(MiddlewareMixin):
    """
    检查用户的url请求是否是其权限范围内
    """
    def process_request(self, request):

        request_url = request.path_info
        permission_url = request.session.get(settings.SESSION_PERMISSION_URL_KEY)

        for reg in settings.SAFE_URL:
            if re.match(reg, request_url):
                return None

        if not permission_url:
            print('该用户尚未注册')
            return redirect('/login/')

        flag = False

        for item in permission_url:
            reg = "^%s$" % item.get("permissions__url")
            print(reg)
            if re.match(reg, request_url):
                flag = True
                break

        if not flag:
            return HttpResponse("没有访问权限！")
